from sqlalchemy import Column, Integer, String, Text, Boolean, DateTime, ForeignKey, Enum
from sqlalchemy.sql import func
import enum
import uuid
from datetime import datetime

from app.db.base import Base

def generate_uuid():
    return str(uuid.uuid4())

class JobStatus(str, enum.Enum):
    QUEUED = "queued"
    STARTING = "starting"
    RUNNING = "running"
    COMPLETED = "completed"
    FAILED = "failed"
    STOPPED = "stopped"

class JobType(str, enum.Enum):
    SPIDER_RUN = "spider_run"
    DEPENDENCY_INSTALLATION = "dependency_installation"

class Spider(Base):
    __tablename__ = "spiders"
    
    id = Column(String(36), primary_key=True, default=generate_uuid)
    name = Column(String(100), nullable=False, unique=True, index=True)
    description = Column(Text, nullable=True)
    code_path = Column(String(255), nullable=False)
    dependencies_path = Column(String(255), nullable=True)
    created_at = Column(DateTime, default=datetime.now)
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)

class Job(Base):
    __tablename__ = "jobs"
    
    id = Column(String(36), primary_key=True, default=generate_uuid)
    spider_id = Column(String(36), ForeignKey("spiders.id"), nullable=False)
    status = Column(Enum(JobStatus), default=JobStatus.QUEUED)
    job_type = Column(Enum(JobType), default=JobType.SPIDER_RUN)
    created_at = Column(DateTime, default=datetime.now)
    started_at = Column(DateTime, nullable=True)
    completed_at = Column(DateTime, nullable=True)
    exit_code = Column(Integer, nullable=True)
    error_message = Column(Text, nullable=True)
    container_id = Column(String(100), nullable=True)
    log_path = Column(String(255), nullable=True)

class Schedule(Base):
    __tablename__ = "schedules"
    
    id = Column(String(36), primary_key=True, default=generate_uuid)
    spider_id = Column(String(36), ForeignKey("spiders.id"), nullable=False)
    cron_expression = Column(String(100), nullable=False)
    description = Column(Text, nullable=True)
    enabled = Column(Boolean, default=True)
    created_at = Column(DateTime, default=datetime.now)
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)
    last_run_at = Column(DateTime, nullable=True)
    next_run_at = Column(DateTime, nullable=True)